    //
//  MyTabBarViewController.m
//  UIFace
//
//  Created by zhu lin on 12/8/11.
//  Copyright 2011 Zhulin. All rights reserved.
//

#import "MyTabBarViewController.h"

#import "BrandsViewController.h"
#import "ModalLoading.h"

NSString * const ZLViewControllerSharedFunction = @"sharedViewController";
NSString * const ZLNetWorkStateKey = @"networkstate";

@interface MyTabBarViewController ()
@end


@implementation MyTabBarViewController

static NSArray * appTabViewNames;

+ (void)initialize
{
    appTabViewNames = [[NSArray alloc] initWithObjects:
                       @"BrandsViewController",
                       @"PriceSelectorViewController",
                       @"CalculatorViewController",
                       @"CarComparatorViewController",
                       @"MoreViewController",
                       nil];
}

+ (NSString *)getTabIndexViewName:(ZLTabIndex)index
{
	return [appTabViewNames objectAtIndex:index];
}

+ (MyTabBarViewController *) sharedMyTabBarViewController
{
	static MyTabBarViewController * sMyTabBarViewController;
	
	if (sMyTabBarViewController == nil) {
		@synchronized (self) {
			sMyTabBarViewController = [[MyTabBarViewController alloc] init];
		}
	}
	return sMyTabBarViewController;
}

- (id)init
{
    self = [super init];
    if (self) {
		NSMutableArray * controllers = [NSMutableArray array];
        
		for (int i = 0; i < [appTabViewNames count]; i++) {
			NSString * tabItemName = [appTabViewNames objectAtIndex:i];
			SEL selector = NSSelectorFromString(ZLViewControllerSharedFunction);
			UIViewController * vc = [NSClassFromString(tabItemName) performSelector:selector];
			UINavigationController * nav = [[UINavigationController alloc] initWithRootViewController:vc];
			[controllers addObject: nav];
			[nav release];
		}
		self.viewControllers = controllers;
		self.customizableViewControllers = controllers;
		
		NSNotificationCenter * nc = [NSNotificationCenter defaultCenter];
		[nc addObserver:self selector:@selector(listBaseInfo:) name:ZLWillListContactsNote object:nil];
    }
    return self;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [UIDevice scheduleReachabilityWatcher:self];
}

- (void)viewDidUnload
{
	[super viewDidUnload];
}


- (void)dealloc {
	NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
	[nc removeObserver:self];
	[UIDevice unscheduleReachabilityWatcher];
    [super dealloc];
}

#pragma mark -
#pragma mark Refresh Badge
- (void)addBadges:(NSString *)badge atIndex:(NSUInteger)index
{
	if (badge && ![badge isEqualToString:@"0"]) {
		[[[self.tabBar items] objectAtIndex:index] setBadgeValue:badge];
	} else {
		[[[self.tabBar items] objectAtIndex:index] setBadgeValue:nil];
	}
}

#pragma mark -
#pragma mark NetworkStatus

- (void)reachabilityChanged
{
	NSNumber * netWorkState = nil;
	NSString * autoLoginFlag = [ZLUserInfoDefault getUserInfoByKey:ZLAccountStateShouldAutoLogIn];
	if ([UIDevice networkAvailable] && autoLoginFlag) {
		if (![ZLUserInfoDefault getUserInfoByKey:ZLListInfoSucFlagContacts]) {
			[self listContacts];
		}
		if (![ZLUserInfoDefault getUserInfoByKey:ZLListInfoSucFlagBlocked]) {
			[self listBlocked];
		}
		if (![ZLUserInfoDefault getUserInfoByKey:ZLListInfoSucFlagGroup]) {
			[self listGroups];
		}
		netWorkState = [NSNumber numberWithBool:YES];
	} else {
		netWorkState = [NSNumber numberWithBool:NO];
	}
	NSDictionary * userInfo = [NSDictionary dictionaryWithObject:netWorkState forKey:ZLNetWorkStateKey];

	NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
	[nc postNotificationName:ZLNetworkStateChangeNote object:self userInfo:userInfo];
}

#pragma mark -
#pragma mark List contacts

- (void)uploadAddressBook
{
	NSAutoreleasePool * pool;
    pool = [[NSAutoreleasePool alloc] init];
	int num = 0;
	while ([ZLABConstructor hasMoreContacts:num]) {
		NSString * json = [ZLABConstructor assembleABJson:num perNum:50];
		[[ZLHTTPServer sharedZLHTTPServer] uploadContacts:json andDelegate:nil];
		num += 50;
	}
	[pool drain];
}

- (void)listBaseInfo:(NSNotification *)note
{
	[self addLoadingLabel:ZLLoadingSuperViewTypeSelfView isAnimate:YES labelText:@"准备服务..."];
	[self listContacts];
	[self listBlocked];
	[self listGroups];
}

- (void)listContacts
{
	[[ZLHTTPServer sharedZLHTTPServer] list:nil force:1 andDelegate:self];
}

- (void)listBlocked
{
	[[ZLHTTPServer sharedZLHTTPServer] listBlockedDelegate:self];
}

- (void)listGroups
{
	[[ZLHTTPServer sharedZLHTTPServer] groupList:self];
}

- (void)doneList:(NSString *)json
{
	[[ZLContactsService sharedZLContactsService] addOrUpdateMultiContactsAndMultiSegments2DB:json];
	[ZLUserInfoDefault setUserInfo:@"YES" forKey:ZLListInfoSucFlagContacts];
	//[self setSelectedIndex:ZLTabIndexContactsList];
}

- (void)doneBlockedList:(NSString *)json
{
	[ZLUserInfoDefault setUserInfo:@"YES" forKey:ZLListInfoSucFlagBlocked];
	[[ZLContactsService sharedZLContactsService] addOrUpdateMultiContacts2DB:json];
}

- (void)doneGroupList:(NSString *)json
{
	[ZLUserInfoDefault setUserInfo:@"YES" forKey:ZLListInfoSucFlagGroup];
	[[ZLGroupsService sharedGroupsService] addOrUpdateMultiGroupsInDB:json isSuggest:NO];
}

#pragma mark -
#pragma mark ZLHTTPPostDelegate
- (void)doneRequest:(NSDictionary *)res error:(NSError *)err
{
	int sc = [[res objectForKey:[ZLHTTPConsts getHTTPProtocolKey:ZLHTTPProtocolServerCode]] intValue];
	int apic = [[res objectForKey:[ZLHTTPConsts getHTTPProtocolKey:ZLHTTPProtocolAPICode]] intValue];
	
	if (sc == ZLHTTPServerContact && apic == ZLContactAPIList) {
		if (err) {
			ZLLogError(@"%d %@",apic,[err localizedDescription]);
			[self removeLoadingLabelFrom:ZLLoadingSuperViewTypeSelfView withAnimate:YES andText:[err localizedDescription] resultType:NO];
		} else {
			NSString * json = [res objectForKey:[ZLHTTPConsts getHTTPProtocolKey:ZLHTTPProtocolJson]];
			[self doneList:json];
			[self removeLoadingLabelFrom:ZLLoadingSuperViewTypeSelfView withAnimate:YES andText:@"开始飞波吧" resultType:YES];
		}
		[self performSelectorInBackground:@selector(uploadAddressBook) withObject:nil];
	}
	
	if (sc == ZLHTTPServerContact && apic == ZLContactAPIListblocked) {
		if (err) {
			ZLLogError(@"%d %@",apic,[err localizedDescription]);
		} else {
			NSString * json = [res objectForKey:[ZLHTTPConsts getHTTPProtocolKey:ZLHTTPProtocolJson]];
			[self doneBlockedList:json];
		}
	}
	if (sc == ZLHTTPServerGroup && apic == ZLGroupAPIList) {
		if (err) {
			ZLLogError(@"%d %@",apic,[err localizedDescription]);
		} else {
			NSString * json = [res objectForKey:[ZLHTTPConsts getHTTPProtocolKey:ZLHTTPProtocolJson]];
			[self doneGroupList:json];
		}
	}
}

@end
